<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">

<head>
    <meta charset="UTF-8">
    <title>多人聊天室</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.7.2/css/all.min.css" rel="stylesheet">
</head>

<body class="bg-gray-100">
<div class="container mx-auto py-8">
    <h1 class="text-3xl font-bold text-center mb-6">多人聊天室</h1>
    <div class="bg-white p-6 rounded-lg shadow-md mb-6">
        <div class="overflow-y-auto h-64" id="chat-messages">
            <!-- 初始消息显示区域 -->
            <div th:each="message : ${messages}" class="mb-2">
                <p class="text-gray-700 break-words" th:text="${message}"></p>
            </div>
        </div>
    </div>
    <form id="chat-form" action="#" th:action="@{/chat}" method="post" class="flex space-x-4">
        <input type="text" name="name" placeholder="用户名" class="border border-gray-300 p-2 rounded flex-1"
               required>
        <input type="text" name="msg" placeholder="消息" class="border border-gray-300 p-2 rounded flex-3"
               required>
        <button type="submit" class="bg-blue-500 text-white p-2 rounded hover:bg-blue-600">发送</button>
    </form>
</div>
<script>
    document.getElementById('chat-form').addEventListener('submit', function (e) {
        e.preventDefault();
        const nameInput = document.querySelector('input[name="name"]');
        const msgInput = document.querySelector('input[name="msg"]');
        const name = nameInput.value;
        const msg = msgInput.value;

        if (name.trim() === '' || msg.trim() === '') {
            return;
        }

        const formData = new FormData();
        formData.append('name', name);
        formData.append('msg', msg);

        fetch(this.action, {
            method: 'POST',
            body: formData
        })
            .then(response => response.text())
            .then(html => {
                const parser = new DOMParser();
                const doc = parser.parseFromString(html, 'text/html');
                const newMessages = doc.querySelectorAll('#chat-messages p');
                const chatMessages = document.getElementById('chat-messages');
                // 清空当前消息列表容器
                chatMessages.innerHTML = '';
                // 直接添加新消息
                newMessages.forEach(message => {
                    chatMessages.appendChild(message.cloneNode(true));
                });
                nameInput.value = '';
                msgInput.value = '';
            })
            .catch(error => console.error('Error:', error));
    });
</script>
</body>

</html>